package top.xxyu;

import ch.ethz.ssh2.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class SSHWindows {

    private static final int  BUFFER_SIZE = 2 * 1024;
    private final static Logger logger = LoggerFactory.getLogger(SSHWindows.class);

    private final static String uploadType = "uploadType";
    private final static String downloadType = "downloadType";
    private final static String separator = ",";
    private static Connection conn;

    public static void main(String[] args) {
        RemoteConnect remoteConnect = new RemoteConnect();
        remoteConnect.setIp("172.20.107.50");
        remoteConnect.setPassword("jx111111");
        remoteConnect.setUserName("sup.bj4750");
        SSHWindows.login(remoteConnect);
        String s = SSHWindows.execConmand(SSHWindows.conn, "netstat -ano | findstr 80");
        String[] tcps = s.split("TCP");
//        System.out.println(s);
        for (int i = 0; i < tcps.length; i++) {
//            System.out.println(tcps[i]);
            if(tcps[i].contains("0.0.0.0:80 ")){
                String pid = tcps[i].substring(tcps[i].length() - 7);
//                System.out.println(tcps[i].substring(tcps[i].length() -7));
//                s = SSHWindows.execConmand(SSHWindows.conn, "taskkill /f /pid "+pid);
                System.out.println(tcps[i]);
                System.out.println(pid);
                s = tcps[i];
//                System.out.println(s);

            }
        }
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        String s = SSHWindows.execConmand(SSHWindows.conn, "sc query tomcat6");
        System.out.println(s);

        SSHWindows.conn.close();

    }


    static ConfigBean buildConfigBean(String configStr) {

        ConfigBean configBean = null;
        if(StringUtils.isNotEmpty(configStr)) {
            String [] configArray = StringUtils.split(configStr,separator);
            //判断是否为上传类型up
            if(uploadType.equals(configArray[1])) {
                //#up;服务器IP地址;端口;服务器用户名;服务器密码;本地文件夹的路径;服务器保存地址;服务器保存文件名

                configBean = new ConfigBean();
                configBean.setType(uploadType);
                configBean.setAddress(configArray[2]);
                configBean.setPort(configArray[3]);
                configBean.setServerUserName(configArray[4]);
                configBean.setServerPassword(configArray[5]);
                configBean.setLocalFilePath(configArray[6]);
                configBean.setServerSavePath(configArray[7]);
                configBean.setServerSaveFileName(configArray[8]);
            }else {
                //上传类型down
                //#down;服务IP地址;端口;服务器用户名;服务器密码;服务器文件夹的路径;本地保存地址;本地保存文件名
                configBean = new ConfigBean();
                configBean.setType(downloadType);
                configBean.setAddress(configArray[2]);
                configBean.setPort(configArray[3]);
                configBean.setServerUserName(configArray[4]);
                configBean.setServerPassword(configArray[5]);
                configBean.setServerFilePath(configArray[6]);
                configBean.setLocalSavePath(configArray[7]);
                configBean.setLocalSaveFileName(configArray[8]);
            }
        }
        return configBean;
    }

    public static Boolean login(RemoteConnect remoteConnect) {
        boolean flag = false;
        try {
            conn = new Connection(remoteConnect.getIp());
            conn.connect();// 连接
            String id_rsa111 = Thread.currentThread().getContextClassLoader().getResource("id_rsa_2048-116").getPath();
            File file = new File(id_rsa111);
            flag = conn.authenticateWithPublicKey(remoteConnect.getUserName(), file,"");// 认证
            if (flag) {
                logger.info("认证成功！");
                System.out.println("authenticate sucessed");
            } else {
                logger.info("认证失败！");
                conn.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 创建链接
     * @param ip
     * @return
     */
    public Connection connect(String ip){
        Connection connection= new Connection(ip);
        try {
            connection.connect();
            return connection;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 登录
     * @param connection
     * @param userName
     * @param passWord
     * @return
     */
    public boolean isAuthenticated(Connection connection, String userName, String passWord){
        //利用用户名和密码进行授权
        boolean isAuthenticated = false;
        try {
            isAuthenticated = connection.authenticateWithPassword(userName, passWord);
            if(isAuthenticated ==false){
                System.out.println("Authorication failed");
                throw new IOException("Authorication failed");
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String execConmand(Connection connection,String command){
        //打开会话,执行命令
        Session session = null;
        InputStream stdout = null;
        BufferedReader br = null;
        StringBuilder console = new StringBuilder();
        try {
            session = connection.openSession();

            if(StringUtils.isNotEmpty(command)) {
                String encodeSet = "";
                session.execCommand(encodeSet+command);
                System.out.println(command);
                stdout = new StreamGobbler(session.getStdout());
                br = new BufferedReader(new InputStreamReader(stdout));
                while(true){
                    String line = br.readLine();
                    if(line==null) break;
                    System.out.println(line);
                    console.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(null != br) {
                    br.close();
                }
                if(null != stdout) {
                    stdout.close();
                }
                if(null != session) {
                    session.close();
                }
//                if(null != connection) {
//                    connection.close();
//                }
            } catch (IOException e) {

                e.printStackTrace();
            }
        }
        return console.toString();
    }

    /**
     * 在远程windows server要执行的bat命令
     * @param config 配置信息
     * @param command 远程windows server要执行的命令
     */
    public void execConmand(ConfigBean config,String command) {

        Connection connection = null;
        Session session = null;
        InputStream stdout = null;
        BufferedReader br = null;

        if(null != config) {
            try{
                //建立连接
                connection= new Connection(config.getAddress());
                connection.connect();
                //利用用户名和密码进行授权
                boolean isAuthenticated = connection.authenticateWithPassword(
                        config.getServerUserName(), config.getServerPassword());
                if(isAuthenticated ==false){
                    System.out.println("Authorication failed");
                    throw new IOException("Authorication failed");
                }
                //打开会话,执行命令
                session = connection.openSession();
                if(StringUtils.isNotEmpty(command)) {
                    String encodeSet = "CHCP 65001 ;";
                    session.execCommand(encodeSet+command);
                    stdout = new StreamGobbler(session.getStdout());
                    br = new BufferedReader(new InputStreamReader(stdout));
                    while(true){
                        String line = br.readLine();
                        if(line==null) break;
		                System.out.println(line);
                    }
                }
            }catch(IOException e){
                e.printStackTrace();
                System.out.println("can not access the remote machine");
            }finally {
                try {
                    if(null != br) {
                        br.close();
                    }
                    if(null != stdout) {
                        stdout.close();
                    }
                    if(null != session) {
                        session.close();
                    }
                    if(null != connection) {
                        connection.close();
                    }
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 执行脚本
     *
     * @param cmds
     * @return
     * @throws Exception
     */
    public int exec2(ConfigBean config,String cmds)  {
        InputStream stdOut = null;
        InputStream stdErr = null;
        String outStr = "";
        String outErr = "";
        int ret = -1;
        try {
            Connection conn = null;
            conn= new Connection(config.getAddress());
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(
                    config.getServerUserName(), config.getServerPassword());
            if(isAuthenticated){
                Session session = conn.openSession();
                // 建立虚拟终端
                session.requestPTY("bash");
                // 打开一个Shell
                session.startShell();
                stdOut = new StreamGobbler(session.getStdout());
                stdErr = new StreamGobbler(session.getStderr());
                BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdOut));
                BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stdErr));

                // 准备输入命令
                PrintWriter out = new PrintWriter(session.getStdin());
                // 输入待执行命令
                out.println(cmds);
                out.println("exit");
                // 6. 关闭输入流
                out.close();
                // 7. 等待，除非1.连接关闭；2.输出数据传送完毕；3.进程状态为退出；4.超时
                session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS , 30000);
                System.out.println("Here is the output from stdout:");
                while (true)
                {
                    String line = stdoutReader.readLine();
                    if (line == null)
                        break;
                    System.out.println(line);
                }
                System.out.println("Here is the output from stderr:");
                while (true)
                {
                    String line = stderrReader.readLine();
                    if (line == null)
                        break;
                    System.out.println(line);
                }
                /* Show exit status, if available (otherwise "null") */
                System.out.println("ExitCode: " + session.getExitStatus());
                ret = session.getExitStatus();
                session.close();/* Close this session */
                SSHWindows.conn.close();/* Close the connection */

            } else {
                throw new Exception("登录远程机器失败" ); // 自定义异常类 实现略
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
            IOUtils.closeQuietly(stdOut);
            IOUtils.closeQuietly(stdErr);
        }
        return ret;
    }

    public static void scpPut(String ip, String userName, String password, String localFile, String remoteDir)
            throws IOException {

        RemoteConnect remoteConnect = new RemoteConnect();
        remoteConnect.setIp(ip);
        remoteConnect.setUserName(userName);
        remoteConnect.setPassword(password);

        if (login(remoteConnect)) {
            SCPClient client = new SCPClient(conn);
            //判断远程服务器文件夹是否存在，若不在，需自动创建 todo
            client.put(localFile, remoteDir);
            conn.close();
        }
    }
    public static void scpPut(ConfigBean config)
            throws IOException {
        SSHWindows.scpPut(config.getAddress(), config.getServerUserName(),
                config.getServerPassword(), config.getLocalFilePath(),
                config.getServerSavePath());

    }





    public static void scpGet(String ip, String userName, String password, String remoteFile, String localDir,String fileName)
            throws IOException {
        File file = new File(localDir);
        if(!file.exists()) {
            file.mkdirs();
        }
        RemoteConnect remoteConnect = new RemoteConnect();
        remoteConnect.setIp(ip);
        remoteConnect.setUserName(userName);
        remoteConnect.setPassword(password);

        if (login(remoteConnect)) {
            SCPClient client = new SCPClient(conn);
            //通过流的方式解决中文乱码问题
            OutputStream out = new FileOutputStream(localDir + fileName);
//            client.get(remoteFile, out);
//			client.get(remoteFile, localDir);
            conn.close();
            out.close();
        }
    }



    /**
     * 压缩成ZIP 方法1
     * @param srcDir 压缩文件夹路径
     * @param out    压缩文件输出流
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     *                          false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
            throws RuntimeException{

        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("finish zip " + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
           * 递归压缩方法
     83      * @param sourceFile 源文件
     84      * @param zos        zip输出流
     85      * @param name       压缩后的名称
     86      * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     87      *                          false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     88      * @throws Exception
           */
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                   boolean KeepDirStructure) throws Exception{
                byte[] buf = new byte[BUFFER_SIZE];
                 if(sourceFile.isFile()){
                         // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
                         zos.putNextEntry(new ZipEntry(name));
                         // copy文件到zip输出流中
                         int len;
                         FileInputStream in = new FileInputStream(sourceFile);
                         while ((len = in.read(buf)) != -1){
                                 zos.write(buf, 0, len);
                             }
                         // Complete the entry
                         zos.closeEntry();
                         in.close();
                     } else {
                         //是文件夹
                         File[] listFiles = sourceFile.listFiles();
                         if(listFiles == null || listFiles.length == 0){
                                 // 需要保留原来的文件结构时,需要对空文件夹进行处理
                                 if(KeepDirStructure){
                                         // 空文件夹的处理
                                         zos.putNextEntry(new ZipEntry(name + "/"));
                                         // 没有文件，不需要文件的copy
                                         zos.closeEntry();
                                     }

                             }else {
                                 for (File file : listFiles) {
                                         // 判断是否需要保留原来的文件结构
                                         if (KeepDirStructure) {
                                                 // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                                                 // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                                                 compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                                             } else {
                                                 compress(file, zos, file.getName(),KeepDirStructure);
                                             }

                                     }
                             }
                     }
             }



    public static void unZipFiles(File zipFile, String descDir) throws IOException {

        ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));//解决中文文件夹乱码
        String name = zip.getName().substring(zip.getName().lastIndexOf('\\')+1, zip.getName().lastIndexOf('.'));

        File pathFile = new File(descDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }

        for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = (descDir + name +"/"+ zipEntryName).replaceAll("\\*", "/");

            // 判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if (new File(outPath).isDirectory()) {
                continue;
            }
            // 输出文件路径信息
//			System.out.println(outPath);

            FileOutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();

        }
        zip.close();
        if(zipFile.exists()) {
            //4.删除本地临时文件zip
            boolean flag = zipFile.delete();
        }
        System.out.println("******************unzip finished********************");
        return;
    }


}
